package com.mjh.zhujianju.controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.enums.EUserRoleType;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.pojo.AjaxResult;
import com.livew.framework.pojo.LoginUserInfo;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTStringUtils;
import com.mjh.zhujianju.model.visit.VisitUserEO;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.base.UserExtendService;
import com.mjh.zhujianju.service.visit.VisitUserService;
import com.mjh.zhujianju.util.ApiConstant;
import com.mjh.zhujianju.util.JsonResult;
import com.mjh.zhujianju.util.ShiroEncryption;
import com.mjh.zhujianju.vo.agency.DeptUserVO;
import com.mjh.zhujianju.vo.base.SysUserVO;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;

@RestController
@RequestMapping("api")
@Api("登录接口")
public class LoginController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private SysUserService userService;
	
	@Resource
	private UserExtendService userExtendService;

	@Autowired
	private VisitUserService visitUserService;
	
	@Resource
	private DeptUserService  deptUserService ;
	

	@Autowired
	private WxMaService wxService;

    @ApiOperation(value="登录->用户登录", notes="根据手机号，密码，openid 三个参数走登陆流程")
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ApiImplicitParam(name="用户登陆", value="SysUserVO", required = true, dataType = "SysUserVO")
	public AjaxResult login( @RequestBody SysUserVO user){
    	if (user == null || XTStringUtils.isEmpty(user.getUsername()) || XTStringUtils.isEmpty(user.getPassword())) {
			return AjaxResult.getResult(Boolean.FALSE, "用户名或密码错误！");
		}
		Subject subject = SecurityUtils.getSubject();
		SysUserVO vo = null;
		try {
			// 已登陆则 跳到首页
//			if (subject.isAuthenticated()) {
//				LoginUserInfo info  = XTCurrentUser.getCurrentUser();
//				vo = userExtendService.getInfo(info.getId());
//				return AjaxResult.getResult(Boolean.TRUE, "登录成功");
//			}
			String password = ShiroEncryption.encrptText(user.getPassword());
			String type = EUserRoleType.user.getCode();
			// 身份验证 
			subject.login(new UsernamePasswordToken(user.getUsername()+"==="+type, password));
			LoginUserInfo info  = XTCurrentUser.getCurrentUser();
			vo = userExtendService.getInfo(info.getId());
		} catch (AuthenticationException e) {
			// 身份验证失败
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		Serializable sId = 	SecurityUtils.getSubject().getSession().getId();
		System.out.println("token:   "+sId);
		if(sId!=null) {
			vo.setToken(sId.toString());
		}
		LoginUserInfo info = XTCurrentUser.getCurrentUser();
		if(info!=null) {
		DeptUserVO dept =	deptUserService.getDeptByUserId(info.getId());
		if(dept!=null) {
			info.setDeptId(dept.getDeptId());
			info.setDeptName(dept.getDeptName());
		}
		}
		vo.setDeptId(info.getDeptId());
		return AjaxResult.getResult(Boolean.TRUE, "登录成功",vo);

	}
    
    
    @ApiOperation(value="信访登录->用户登录")
    @RequestMapping(value = "visitLogin", method = RequestMethod.POST)
    @ApiImplicitParam(name="用户登陆", value="SysUserVO", required = true, dataType = "SysUserVO")
    public AjaxResult visitLogin( @RequestBody SysUserVO user){
    	if (user == null || XTStringUtils.isEmpty(user.getUsername()) || XTStringUtils.isEmpty(user.getPassword())) {
    		return AjaxResult.getResult(Boolean.FALSE, "用户名或密码错误！");
    	}
    	Subject subject = SecurityUtils.getSubject();
    	SysUserVO vo = null;
    	try {
    		// 已登陆则 跳到首页
//			if (subject.isAuthenticated()) {
//				LoginUserInfo info  = XTCurrentUser.getCurrentUser();
//				vo = userExtendService.getInfo(info.getId());
//				return AjaxResult.getResult(Boolean.TRUE, "登录成功");
//			}
    		String password = ShiroEncryption.encrptText(user.getPassword());
    		String type = EUserRoleType.visitor.getCode();
    		// 身份验证 
    		subject.login(new UsernamePasswordToken(user.getUsername()+"==="+type, password));
    		LoginUserInfo info  = XTCurrentUser.getCurrentUser();
    		vo = userExtendService.getInfo(info.getId());
    	} catch (AuthenticationException e) {
    		// 身份验证失败
    		return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
    	}catch (XTBusinessException e) {
    		e.printStackTrace();
    		return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
    	}
    	Serializable sId = 	SecurityUtils.getSubject().getSession().getId();
    	if(sId!=null) {
    		vo.setToken(SecurityUtils.getSubject().getSession().getId().toString());
    	}
    	return AjaxResult.getResult(Boolean.TRUE, "登录成功",vo);
    	
    }

	@ApiOperation(value="登录->用户登录", notes="根据手机号，密码，openid 三个参数走登陆流程")
		@RequestMapping(value = "loginVisit", method = RequestMethod.POST)
	@ApiImplicitParam(name="用户登陆", value="SysUserVO", required = true, dataType = "SysUserVO")
	public AjaxResult loginVisit( @RequestBody SysUserVO user){
		if (user == null || XTStringUtils.isEmpty(user.getUsername()) || XTStringUtils.isEmpty(user.getPassword())) {
			return AjaxResult.getResult(Boolean.FALSE, "用户名或密码错误！");
		}
		Subject subject = SecurityUtils.getSubject();
		SysUserVO vo = null;
		try {
			// 已登陆则 跳到首页
//			if (subject.isAuthenticated()) {
//				LoginUserInfo info  = XTCurrentUser.getCurrentUser();
//				vo = userExtendService.getInfo(info.getId());
//				return AjaxResult.getResult(Boolean.TRUE, "登录成功");
//			}
			String password = ShiroEncryption.encrptText(user.getPassword());
			String type = EUserRoleType.visitor.getCode();
			// 身份验证
			subject.login(new UsernamePasswordToken(user.getUsername()+"==="+type, password));
			LoginUserInfo info  = XTCurrentUser.getCurrentUser();
			vo = userExtendService.getInfo(info.getId());
		} catch (AuthenticationException e) {
			// 身份验证失败
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		Serializable sId = 	SecurityUtils.getSubject().getSession().getId();
		if(sId!=null) {
			vo.setToken(SecurityUtils.getSubject().getSession().getId().toString());
		}
		return AjaxResult.getResult(Boolean.TRUE, "登录成功",vo);

	}

    @ApiOperation(value="登录->获取用户openid", notes="根据code获取用户openid")
	@RequestMapping(value = "getOpenid/{code}", method = RequestMethod.GET)
    @ApiImplicitParam(name = "code", value = "微信code", required = true, dataType = "String", paramType = "path")
	public AjaxResult getOpenid(@PathVariable(value = "code")String code) {
		JsonResult result = new JsonResult();
		try {
			WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
			this.logger.info(session.getSessionKey());
			this.logger.info(session.getOpenid());
			result.setResult(session.getOpenid());
			result.setStatus(ApiConstant.MSG_SUCCESS);
		return AjaxResult.getResult(result);
		} catch (WxErrorException e) {
			this.logger.error(e.getMessage(), e);
			result.setResult(e.getClass().getName() + ":" + e.getMessage());
			result.setStatus("error");
			e.printStackTrace();
			return AjaxResult.getResult(result);
		}
	}

	@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
	@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	public ResponseEntity<JsonResult> getUserById(@PathVariable(value = "id") Integer id) {
		JsonResult r = new JsonResult();
		List<SysUser> userList = Lists.newArrayList();
		try {
			userList = userService.getAll();
			r.setResult(userList);
			r.setStatus("ok");
		} catch (Exception e) {
			r.setResult(e.getClass().getName() + ":" + e.getMessage());
			r.setStatus("error");
			e.printStackTrace();
		}
		return ResponseEntity.ok(r);
	}

	@ApiOperation(value = "信访->修改密码", notes = "信访用户修改登录密码")
	@RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
	@ApiImplicitParam(name = "用户实体类", value = "sysUserVO", required = true, dataType = "SysUserVO")
	public ResponseEntity<JsonResult> modifyPassword(@RequestBody SysUserVO sysUserVO) {
		JsonResult result = new JsonResult();
		try{
			LoginUserInfo info = XTCurrentUser.getCurrentUser();
			SysUser sysUser = new SysUser();
			BeanUtils.copyProperties(sysUserVO, sysUser);
			SysUser user = userService.getByPrimaryKey(info.getId());
			if (user == null) {
				result.setResult("修改失败");
				result.setStatus(ApiConstant.MSG_ERROR);
			} else {
				if(sysUserVO==null||XTStringUtils.isEmpty(sysUserVO.getPassword())||XTStringUtils.isEmpty(sysUserVO.getRemark3())) {
					result.setResult("修改失败");
					result.setStatus(ApiConstant.MSG_ERROR);
				}
				sysUser.setRemark3(ShiroEncryption.encrptText(sysUser.getRemark3()));
				sysUser.setPassword(ShiroEncryption.encrptText(sysUser.getPassword()));
				sysUser.setId(user.getId());
				userService.updatePwd(sysUser);
				result.setResult("修改成功");
				result.setStatus(ApiConstant.MSG_SUCCESS);
			}
		}catch(XTBusinessException e){
			result.setResult(e.getMessage());
			result.setStatus(ApiConstant.MSG_ERROR);
		}

		return ResponseEntity.ok(result);
	}


    @ApiOperation(value = "信访->用户注册", notes = "信访用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiImplicitParam(name = "用户实体类", value = "sysUserVO", required = true, dataType = "SysUserVO")
    public ResponseEntity<JsonResult> register(@RequestBody SysUserVO sysUserVO) {
        JsonResult result = new JsonResult();
        try{
            if (sysUserVO == null || StringUtils.isEmpty(sysUserVO.getPassword())
                    || StringUtils.isEmpty(sysUserVO.getPhone())){
                result.setResult("用户名或密码为空");
                result.setStatus(ApiConstant.MSG_ERROR);
                return ResponseEntity.ok(result);
            }

            SysUser sysUser = userService.getUserByPhone(sysUserVO.getPhone());
            if (null != sysUser){
                result.setResult("当前手机号已存在");
                result.setStatus(ApiConstant.MSG_REPEAT);
                return ResponseEntity.ok(result);
            }
			sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVO,sysUser);
            sysUser.setType(EUserRoleType.visitor.getCode());
			sysUser.setPassword(ShiroEncryption.encrptText(sysUser.getPassword()));
			sysUser.setUsername(sysUser.getPhone());
            userService.saveSelective(sysUser);

            //保存到信访用户表
			if(sysUser.getId() == null){
				result.setResult("注册失败");
				result.setStatus(ApiConstant.MSG_ERROR);
				return ResponseEntity.ok(result);
			}
			VisitUserEO visitUserEO = new VisitUserEO();
			visitUserEO.setUserId(sysUser.getId());
			visitUserEO.setName(sysUserVO.getNickname());
			visitUserEO.setSex(String.valueOf(sysUserVO.getSex()));
			visitUserEO.setIdCard(sysUserVO.getId_num());
			visitUserEO.setProvinceName(sysUserVO.getArea().get(0));
			visitUserEO.setCityName(sysUserVO.getArea().get(1));
			visitUserEO.setCountyName(sysUserVO.getArea().get(2));
			visitUserEO.setDetailAddress(sysUserVO.getAddress());
			visitUserEO.setStatus("1");
			visitUserService.saveInfo(visitUserEO);
            result.setResult("注册成功");
            result.setStatus(ApiConstant.MSG_SUCCESS);
        }catch(XTBusinessException e){
            result.setResult("注册失败");
            result.setStatus(ApiConstant.MSG_ERROR);
        }
        return ResponseEntity.ok(result);
    }

}
